<template>
    <div class="notice-manage">
        <div class="title">
          <h1>公告发布管理</h1>
        </div>
        <div class="content" style="min-height: 100vh;opacity: 0.88;">
          <div class="search-container" style="margin-bottom: 20px;">
          <el-input v-model="searchName" placeholder="按内容搜索公告" style="width: 300px; margin-right: 20px;" />
          <el-button @click="searchProduct">搜索</el-button>
         </div>
        <el-table :data="paginatedData" style="width: 100%">
          <el-table-column prop="no" label="No"  />
          <el-table-column prop="id" label="Id" />
          <el-table-column prop="text" label="Text"   />
          <el-table-column prop="ifplay" label="Ifplay">
          <template v-slot="{ row }">
          <span>{{ row.ifplay === 1 ? '已轮播' : '未轮播' }}</span>
          </template>
          </el-table-column>
          <el-table-column label="Actions">
            <template v-slot="{ row }">
              <el-button @click="editProduct(row)">编辑</el-button>
              <el-button @click="deleteProduct(row.id)" type="danger">删除</el-button>
            </template>
          </el-table-column>
      </el-table>
      <el-pagination
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-size="pageSize"
          :total="filteredData.length"
          layout="total, prev, pager, next, jumper"
        ></el-pagination>
    </div>
      <el-dialog v-model="dialogFormVisible" title="编辑公告" width="500" @close="cancelEdit">
        <el-form :model="editForm">
         <el-form-item label="编号">
          <el-input v-model="editForm.id"></el-input>
          </el-form-item>
          <el-form-item label="文本">
            <el-input v-model="editForm.text" type="number"></el-input>
          </el-form-item>
          <el-form-item label="播放状态">
            <el-radio-group v-model="editForm.ifplay">
              <el-radio :label="1">已轮播</el-radio>
              <el-radio :label="0">未轮播</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="cancelEdit">取消</el-button>
            <el-button type="primary" @click="updateProduct">保存</el-button>
          </div>
        </template>
        </el-dialog>
        <el-dialog v-model="addFormVisible" title="发布公告" width="500" @close="cancelAdd">
          <el-form :model="addForm">
            <el-form-item label="编号">
           <el-input v-model="editForm.id"></el-input>
           </el-form-item>
            <el-form-item label="文本">
              <el-input v-model="addForm.text" type="number"></el-input>
            </el-form-item>
            <el-form-item label="播放状态">
              <el-radio-group v-model="addForm.ifplay">
                <el-radio :label="1">已轮播</el-radio>
                <el-radio :label="0">未轮播</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
          <template #footer>
          <div class="dialog-footer">
            <el-button @click="cancelAdd">取消发布</el-button>
            <el-button type="primary" @click="trueNotice">确认发布</el-button>
          </div>
        </template>
        </el-dialog>
    </div>
</template>
<script setup>
import { ref, computed, onMounted } from 'vue';
import axios from 'axios';
const tableData = ref([]);
const dialogFormVisible = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const editForm = ref({ id: '', text: '', ifplay: 0 });
const searchName = ref('');
const fetchData = async () => {
    try {
      const response = await axios.get('http://localhost:8080/api/notices'); // 获取所有商品
      console.log(response.data);  // 输出返回的数据
      if (Array.isArray(response.data)) {
        tableData.value = response.data.map((notice, index) => ({
          no: index + 1,
          id: notice.id,
          text: notice.text,
          ifplay: notice.ifplay,
        }));
      } else {
        console.error('Expected an array of products but received:', response.data);
      }
    } catch (error) {
      console.error('Error fetching data:', error);
    }
  };
  const searchProduct = () => {
    currentPage.value = 1;  // 重置分页到第一页
  };
  
  const filteredData = computed(() => {
    return tableData.value.filter(notice => {
      return notice.text.toLowerCase().includes(searchName.value.toLowerCase());
    });
  });
  
  const paginatedData = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    return filteredData.value.slice(start, end);
  });
  
  const handleCurrentChange = (page) => {
    currentPage.value = page;
  };
  
  const editProduct = (product) => {
    editForm.value = { ...product };
    dialogFormVisible.value = true;
  };
  const resetEditForm = () => {
    editForm.value = { id: '',text: '', ifplay: 0 }
  };
  const cancelEdit = () => {
    dialogFormVisible.value = false;
    resetEditForm();
  };
  const updateProduct = async () => {
  const formData = new FormData();
  formData.append('text', editForm.value.text);
  formData.append('ifplay', editForm.value.ifplay ? 1 : 0);
  try {
    await axios.put(`http://localhost:8080/api/notices/${editForm.value.id}`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
    });
    await fetchData(); // 刷新表格数据
    dialogFormVisible.value = false;
    resetEditForm(); // 重置表单
  } catch (error) {
    console.error('Error updating product:', error);
  }
};
 
const deleteProduct = async (id) => {
    try {
      await axios.delete(`http://localhost:8080/api/notices/${id}`);
      await fetchData();
    } catch (error) {
      console.error('Error deleting product:', error);
    }
  };
  onMounted(() => {
    fetchData();
  });
</script>
<style scoped>
.notice-manage .title {
    font-size: 2em;
    text-align: center;
    text-shadow: 5px 5px 5px #0e42ff;
  }
  .content {
    background-color: aliceblue;
  }
  
  .search-container {
    text-align: right;
  }
  .newNotice {
    text-align: right;
  }
</style>